﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using BanZuiCloudControlAgent.Utils.Logging;

namespace BanZuiCloudControlAgent.UI
{
    /// <summary>
    /// 日志查看器控件
    /// </summary>
    public partial class LogViewer : UserControl
    {
        private List<LogEntry> _logs = new List<LogEntry>(); // 存储日志条目
        private readonly object _logsLock = new object(); // 日志锁对象
        private const int MaxLogCount = 1000; // 最大日志数量
        private Logger _logger;
        
        // 日志过滤条件
        private DateTime _startDate = DateTime.Today.AddDays(-7);
        private DateTime _endDate = DateTime.Now.AddDays(1);
        private LogLevel? _selectedLevel = null;
        private string _searchText = string.Empty;
        
        /// <summary>
        /// 获取或设置日志开始日期
        /// </summary>
        public DateTime StartDate 
        { 
            get { return _startDate; }
            set 
            { 
                _startDate = value;
                if (dateTimePickerStart != null)
                    dateTimePickerStart.Value = value;
            }
        }
        
        /// <summary>
        /// 获取或设置日志结束日期
        /// </summary>
        public DateTime EndDate 
        { 
            get { return _endDate; }
            set 
            { 
                _endDate = value;
                if (dateTimePickerEnd != null)
                    dateTimePickerEnd.Value = value;
            }
        }
        
        /// <summary>
        /// 获取或设置日志级别过滤
        /// </summary>
        public LogLevel? SelectedLevel
        {
            get { return _selectedLevel; }
            set
            {
                _selectedLevel = value;
                if (comboBoxLevel != null)
                {
                    if (value == null)
                        comboBoxLevel.SelectedIndex = 0;
                    else
                    {
                        switch (value)
                        {
                            case LogLevel.Debug: comboBoxLevel.SelectedIndex = 1; break;
                            case LogLevel.Info: comboBoxLevel.SelectedIndex = 2; break;
                            case LogLevel.Warning: comboBoxLevel.SelectedIndex = 3; break;
                            case LogLevel.Error: comboBoxLevel.SelectedIndex = 4; break;
                            case LogLevel.Fatal: comboBoxLevel.SelectedIndex = 5; break;
                        }
                    }
                }
            }
        }
        
        /// <summary>
        /// 获取或设置搜索文本
        /// </summary>
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                _searchText = value ?? string.Empty;
                if (txtSearch != null)
                    txtSearch.Text = value;
            }
        }

        public LogViewer()
        {
            InitializeComponent();
            
            // 初始化控件
            if (comboBoxLevel != null)
                comboBoxLevel.SelectedIndex = 0;
                
            // 设置日期选择器默认值
            dateTimePickerStart.Value = _startDate;
            dateTimePickerEnd.Value = _endDate;
            
            // 初始化日志记录器
            _logger = LogManager.GetLogger("LogViewer");
            
            // 订阅日志事件
            Logger.LogWritten += Logger_LogWritten;
            
            // 记录初始化完成日志
            _logger.Info("日志查看器初始化完成");
        }
        
        /// <summary>
        /// 处理日志事件
        /// </summary>
        private void Logger_LogWritten(object sender, Logger.LogEventArgs e)
        {
            try
            {
                // 创建日志条目
                var logEntry = new LogEntry
                {
                    Timestamp = e.Timestamp,
                    Level = ParseLogLevel(e.Level),
                    Source = e.LoggerName,
                    Message = e.Message + (e.Exception != null ? $" - {e.Exception.Message}" : "")
                };
                
                // 添加到日志列表
                lock (_logsLock)
                {
                    _logs.Add(logEntry);
                    
                    // 限制日志数量
                    if (_logs.Count > MaxLogCount)
                    {
                        _logs.RemoveRange(0, _logs.Count - MaxLogCount);
                    }
                }
                
                // 如果当前控件可见，则实时更新日志显示
                if (Visible && Parent != null && Parent.Visible && !IsDisposed && IsHandleCreated)
                {
                    // 由于事件可能在非UI线程触发，需要使用Invoke确保在UI线程更新界面
                    if (InvokeRequired)
                    {
                        BeginInvoke(new Action(() => AppendLogToDisplay(logEntry)));
                    }
                    else
                    {
                        AppendLogToDisplay(logEntry);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理日志事件时发生异常: {ex.Message}");
            }
        }
        
        /// <summary>
        /// 解析日志级别
        /// </summary>
        private LogLevel ParseLogLevel(string level)
        {
            switch (level.ToUpper().Trim())
            {
                case "DEBUG":
                    return LogLevel.Debug;
                case "INFO":
                    return LogLevel.Info;
                case "WARN":
                case "WARNING":
                    return LogLevel.Warning;
                case "ERROR":
                    return LogLevel.Error;
                case "FATAL":
                    return LogLevel.Fatal;
                default:
                    return LogLevel.Info;
            }
        }
        
        /// <summary>
        /// 向日志显示区域添加日志
        /// </summary>
        private void AppendLogToDisplay(LogEntry logEntry)
        {
            // 根据筛选条件检查是否应该显示此日志
            if (!ShouldDisplayLog(logEntry))
                return;
                
            // 设置RichTextBox以提高性能
            richTextBoxLogs.SuspendLayout();
            
            // 根据日志级别设置颜色
            Color textColor = GetLogLevelColor(logEntry.Level);
            
            // 添加格式化的日志条目
            string logLine = $"[{logEntry.Timestamp:yyyy-MM-dd HH:mm:ss}] [{logEntry.Level}] [{logEntry.Source}] {logEntry.Message}";
            
            // 在当前位置插入文本
            richTextBoxLogs.SelectionStart = richTextBoxLogs.TextLength;
            richTextBoxLogs.SelectionLength = 0;
            richTextBoxLogs.SelectionColor = textColor;
            richTextBoxLogs.AppendText(logLine + Environment.NewLine);
            
            // 恢复默认颜色
            richTextBoxLogs.SelectionColor = richTextBoxLogs.ForeColor;
            
            // 恢复布局
            richTextBoxLogs.ResumeLayout();
            
            // 滚动到底部
            richTextBoxLogs.SelectionStart = richTextBoxLogs.Text.Length;
            richTextBoxLogs.ScrollToCaret();
        }
        
        /// <summary>
        /// 判断日志是否应该显示
        /// </summary>
        private bool ShouldDisplayLog(LogEntry logEntry)
        {
            return logEntry.Timestamp >= _startDate && 
                   logEntry.Timestamp <= _endDate && 
                   (_selectedLevel == null || logEntry.Level == _selectedLevel) && 
                   (string.IsNullOrEmpty(_searchText) || logEntry.Message.ToLower().Contains(_searchText.ToLower()));
        }
        
        /// <summary>
        /// 根据日志级别获取显示颜色
        /// </summary>
        private Color GetLogLevelColor(LogLevel level)
        {
            switch (level)
            {
                case LogLevel.Debug:
                    return Color.Gray;
                case LogLevel.Info:
                    return Color.Black;
                case LogLevel.Warning:
                    return Color.Orange;
                case LogLevel.Error:
                    return Color.Red;
                case LogLevel.Fatal:
                    return Color.DarkRed;
                default:
                    return Color.Black;
            }
        }
        
        /// <summary>
        /// 显示日志
        /// </summary>
        public void DisplayLogs()
        {
            if (InvokeRequired)
            {
                BeginInvoke(new Action(DisplayLogs));
                return;
            }
            
            // 清空日志显示区域
            richTextBoxLogs.Clear();
            
            // 根据筛选条件过滤日志
            var filteredLogs = FilterLogs();
            
            // 设置RichTextBox以提高性能
            richTextBoxLogs.SuspendLayout();
            
            // 遍历过滤后的日志，按照格式显示
            foreach (var log in filteredLogs)
            {
                // 根据日志级别设置颜色
                Color textColor = GetLogLevelColor(log.Level);
                
                // 添加格式化的日志条目
                string logLine = $"[{log.Timestamp:yyyy-MM-dd HH:mm:ss}] [{log.Level}] [{log.Source}] {log.Message}";
                
                // 在当前位置插入文本
                richTextBoxLogs.SelectionStart = richTextBoxLogs.TextLength;
                richTextBoxLogs.SelectionLength = 0;
                richTextBoxLogs.SelectionColor = textColor;
                richTextBoxLogs.AppendText(logLine + Environment.NewLine);
            }
            
            // 恢复默认颜色
            richTextBoxLogs.SelectionColor = richTextBoxLogs.ForeColor;
            
            // 恢复布局
            richTextBoxLogs.ResumeLayout();
            
            // 滚动到底部
            richTextBoxLogs.SelectionStart = richTextBoxLogs.Text.Length;
            richTextBoxLogs.ScrollToCaret();
        }
        
        /// <summary>
        /// 过滤日志
        /// </summary>
        private List<LogEntry> FilterLogs()
        {
            lock (_logsLock)
            {
                return _logs.Where(log => 
                    log.Timestamp >= _startDate && 
                    log.Timestamp <= _endDate && 
                    (_selectedLevel == null || log.Level == _selectedLevel) && 
                    (string.IsNullOrEmpty(_searchText) || log.Message.ToLower().Contains(_searchText.ToLower()))
                ).ToList();
            }
        }
        
        /// <summary>
        /// 清除日志
        /// </summary>
        public void ClearLogs()
        {
            lock (_logsLock)
            {
                _logs.Clear();
            }
            richTextBoxLogs.Clear();
        }
        
        /// <summary>
        /// 导出日志
        /// </summary>
        public void ExportLogs(string filePath)
        {
            try
            {
                // 导出当前筛选出的日志
                var filteredLogs = FilterLogs();
                
                // 将日志写入文件
                using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.UTF8))
                {
                    foreach (var log in filteredLogs)
                    {
                        writer.WriteLine($"[{log.Timestamp:yyyy-MM-dd HH:mm:ss}] [{log.Level}] [{log.Source}] {log.Message}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出日志时发生错误：{ex.Message}", "导出失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        
        /// <summary>
        /// 筛选按钮点击事件
        /// </summary>
        private void btnFilter_Click(object sender, EventArgs e)
        {
            // 更新筛选条件
            _startDate = dateTimePickerStart.Value;
            _endDate = dateTimePickerEnd.Value;
            _searchText = txtSearch.Text;
            
            // 获取选中的日志级别
            _selectedLevel = null;
            if (comboBoxLevel.SelectedIndex > 0) // 不是"全部"选项
            {
                switch (comboBoxLevel.SelectedIndex)
                {
                    case 1: _selectedLevel = LogLevel.Debug; break;
                    case 2: _selectedLevel = LogLevel.Info; break;
                    case 3: _selectedLevel = LogLevel.Warning; break;
                    case 4: _selectedLevel = LogLevel.Error; break;
                    case 5: _selectedLevel = LogLevel.Fatal; break;
                }
            }
            
            // 显示日志
            DisplayLogs();
        }
        
        /// <summary>
        /// 清除按钮点击事件
        /// </summary>
        private void btnClear_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清除所有日志吗？", "确认清除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ClearLogs();
            }
        }
        
        /// <summary>
        /// 导出按钮点击事件
        /// </summary>
        private void btnExport_Click(object sender, EventArgs e)
        {
            // 创建保存文件对话框
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "日志文件 (*.log)|*.log|文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
            saveDialog.Title = "导出日志";
            saveDialog.DefaultExt = "log";
            saveDialog.FileName = $"BanZuiCloudControl_{DateTime.Now:yyyyMMdd_HHmmss}.log";
            
            if (saveDialog.ShowDialog() == DialogResult.OK)
            {
                ExportLogs(saveDialog.FileName);
                MessageBox.Show($"日志已成功导出到：{saveDialog.FileName}", "导出成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        
        /// <summary>
        /// 控件销毁时取消订阅日志事件
        /// </summary>
        protected override void OnHandleDestroyed(EventArgs e)
        {
            // 取消订阅日志事件
            Logger.LogWritten -= Logger_LogWritten;
            
            base.OnHandleDestroyed(e);
        }

        private void groupBoxFilter_Enter(object sender, EventArgs e) {

        }
    }
} 